package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ArticleServiceMapper;
import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.service.ArticleService;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleServiceMapper articleServiceMapper;
    @Override
    public void add(Article article) {
        //补充属性值
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map =  ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        articleServiceMapper.add(article);

    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, String state, Integer categoryId) {
        //创建PageBean对象，设置分页参数
        PageBean<Article> pb = new PageBean<>();
        //开启分页
        PageHelper.startPage(pageNum,pageSize);
        //调用mapper查询分页后的数据
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> as = articleServiceMapper.list(userId,categoryId,state);
        Page<Article> p = (Page<Article>) as;
        //数据填充
        pb.setItems(p.getResult());
        pb.setTotal(p.getTotal());
        return pb;
    }

    //更新文章
    @Override
    public void put(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleServiceMapper.put(article);
    }

    //查询文章详情
    @Override
    public Article get(Integer id) {
        return articleServiceMapper.get(id);
    }

    @Override
    public void delete(Integer id) {
        articleServiceMapper.delete(id);
    }
}
